"use client";

import { useEffect, useState, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { FileText, User, Calendar, Loader2, Search, Filter, ChevronDown, ChevronUp } from "lucide-react";
import VisitCount from "@/components/visit-count";
import { useLanguage } from "@/context/language-provider";

interface ExamMemory {
  id: string;
  fileName: string;
  timestamp: string;
  exam: string;
  examDate: string;
  grade: string;
  source: string;
  questions: string;
  signature: string;
  international?: boolean;
}

function ViewerPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const examParam = searchParams.get("exam");
  const fileParam = searchParams.get("source");
  const yearParam = searchParams.get("year");
  const examDateParam = searchParams.get("examDate");
  const gradeParam = searchParams.get("grade");
  
  const [memories, setMemories] = useState<ExamMemory[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedExams, setExpandedExams] = useState<string[]>([]);
  const [availableYears, setAvailableYears] = useState<number[]>([]);
  const [selectedYear, setSelectedYear] = useState<string | null>(yearParam);
  const [yearFilterOpen, setYearFilterOpen] = useState(false);
  const { language, isInternational } = useLanguage();

  // 如果有指定的考试参数，记录访问量
  useEffect(() => {
    if (examParam) {
      // 使用 localStorage 来避免重复计数
      const lastVisitKey = `lastExamVisit_${examParam}`;
      const lastVisitTime = localStorage.getItem(lastVisitKey);
      const currentTime = Date.now();
      
      // 如果是首次访问或距离上次访问超过1小时，则记录访问
      if (!lastVisitTime || (currentTime - parseInt(lastVisitTime)) > 3600000) {
        fetch(`/api/metrics?type=exam${isInternational ? '&int=true' : ''}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            examName: examParam,
            examDate: examDateParam || "",
            grade: gradeParam || ""
          }),
        })
        .then(response => response.json())
        .catch(error => console.error('记录考试页面访问出错:', error));
        
        // 更新最后访问时间
        localStorage.setItem(lastVisitKey, currentTime.toString());
      }
    }
  }, [examParam, examDateParam, gradeParam, isInternational]);

  useEffect(() => {
    async function fetchMemories() {
      try {
        // 构建API请求URL
        let url = "/api/memories";
        const params = new URLSearchParams();
        
        if (examParam) {
          params.append("exam", examParam);
        }
        
        if (fileParam) {
          params.append("source", fileParam);
        }
        
        // 添加考试日期和年级参数
        if (examDateParam) {
          params.append("examDate", examDateParam);
        }
        
        if (gradeParam) {
          params.append("grade", gradeParam);
        }
        
        // 添加国际化参数
        if (isInternational) {
          params.append("int", "true");
        }
        
        if (params.toString()) {
          url += `?${params.toString()}`;
        }
        
        console.log("API请求URL:", url);
        console.log("请求参数:", {
          exam: params.get("exam"),
          examDate: examDateParam,
          grade: gradeParam,
          source: fileParam,
          international: isInternational
        });
        
        const response = await fetch(url);
        const data = await response.json();
        
        console.log("API返回数据:", data);
        
        if (data.memories && Array.isArray(data.memories)) {
          setMemories(data.memories);
          
          // 如果只有一个考试，默认展开
          if (examParam) {
            setExpandedExams([examParam]);
          }
          
          // 提取所有可用的年份
          const years = new Set<number>();
          data.memories.forEach((memory: ExamMemory) => {
            const year = parseInt(memory.exam.split(' ')[0]);
            if (!isNaN(year)) {
              years.add(year);
            }
          });
          setAvailableYears(Array.from(years).sort((a, b) => b - a)); // 降序排列年份
        }
      } catch (error) {
        console.error("获取回忆数据失败", error);
      } finally {
        setLoading(false);
      }
    }
    
    fetchMemories();
  }, [examParam, fileParam, examDateParam, gradeParam, isInternational]);

  // 将回忆按考试名称分组
  const groupedMemories = memories.reduce<Record<string, ExamMemory[]>>((groups, memory) => {
    const key = memory.exam;
    if (!groups[key]) {
      groups[key] = [];
    }
    groups[key].push(memory);
    return groups;
  }, {});

  // 获取排序后的考试名称列表 - 按年份倒序排列，并根据选定年份筛选
  const examNames = Object.keys(groupedMemories)
    .filter(name => {
      if (!selectedYear) return true;
      const year = parseInt(name.split(' ')[0]) || 0;
      return year.toString() === selectedYear;
    })
    .sort((a, b) => {
      // 提取年份信息，假设格式为 "2023 课程名称" 或类似格式
      const yearA = parseInt(a.split(' ')[0]) || 0;
      const yearB = parseInt(b.split(' ')[0]) || 0;
      
      // 倒序排列，最新的年份在前
      return yearB - yearA;
    });

  // 切换折叠状态
  const toggleExam = (examName: string) => {
    if (expandedExams.includes(examName)) {
      setExpandedExams(expandedExams.filter(name => name !== examName));
    } else {
      setExpandedExams([...expandedExams, examName]);
    }
  };
  
  // 切换年份筛选
  const handleYearFilter = (year: string | null) => {
    setSelectedYear(year);
    
    // 更新URL参数
    const params = new URLSearchParams(searchParams.toString());
    if (year) {
      params.set("year", year);
    } else {
      params.delete("year");
    }
    
    if (examParam) {
      params.set("exam", examParam);
    }
    
    if (fileParam) {
      params.set("source", fileParam);
    }
    
    if (examDateParam) {
      params.set("examDate", examDateParam);
    }
    
    if (gradeParam) {
      params.set("grade", gradeParam);
    }
    
    // 保持国际化参数
    if (isInternational) {
      params.set("int", "true");
    }
    
    router.push(`/viewer?${params.toString()}`);
    setYearFilterOpen(false);
  };

  return (
    <div className="space-y-6 md:space-y-10 -mx-2 sm:-mx-3 md:-mx-4 lg:-mx-6">
      <div className="space-y-3 md:space-y-4">
        <h1 className="text-2xl md:text-4xl font-bold tracking-tight text-gradient">
          {examParam ? 
            language === "zh" ? 
              `${examParam} 考试回忆` : 
              `${examParam} Exam Memories` 
            : language === "zh" ? 
              "全部考试回忆" : 
              "All Exam Memories"
          }
        </h1>
        <div className="flex flex-col md:flex-row md:items-center gap-2 md:gap-4">
          <p className="text-base md:text-lg max-w-2xl" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
            {language === "zh" ? 
              "查看同学们分享的考试回忆内容" : 
              "View exam memories shared by fellow students"
            }
          </p>
          {examParam && (
            <VisitCount 
              type="exam" 
              examName={examParam}
              examDate={examDateParam || ""}
              grade={gradeParam || ""}
              className="text-muted-foreground" 
            />
          )}
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center py-8 md:py-12">
          <div className="flex flex-col items-center">
            <Loader2 className="h-8 w-8 md:h-10 md:w-10 animate-spin text-primary" />
            <span className="mt-3" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
              {language === "zh" ? "正在加载记忆..." : "Loading memories..."}
            </span>
          </div>
        </div>
      ) : examNames.length === 0 ? (
        <div className="glass-panel flex flex-col items-center justify-center py-8 md:py-12 gap-4 md:gap-6 border-dashed">
          <div className="relative">
            <div className="absolute -inset-6 rounded-full animate-pulse blur-xl"
                 style={{ backgroundColor: 'hsl(var(--primary) / 0.1)' }}></div>
            <Search className="h-12 w-12 md:h-16 md:w-16 relative" style={{ color: 'hsl(var(--primary) / 0.9)' }} />
          </div>
          <div className="text-center space-y-2 md:space-y-3 px-2 sm:px-3 md:px-4">
            <p className="text-xl md:text-2xl font-medium">
              {language === "zh" ? "暂无考试回忆记录" : "No exam memories found"}
            </p>
            <p className="text-sm md:text-base max-w-md" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
              {language === "zh" ? 
                selectedYear 
                  ? `${selectedYear}年暂无考试回忆` 
                  : examParam 
                    ? "这门课程暂时没有回忆" 
                    : "目前还没有任何考试回忆"
                :
                selectedYear 
                  ? `No memories for year ${selectedYear}` 
                  : examParam 
                    ? "No memories for this course yet" 
                    : "No exam memories available yet"
              }
            </p>
            {examParam && (
              <a 
                href={`/submit?exam=${encodeURIComponent(examParam)}${examDateParam ? `&examDate=${encodeURIComponent(examDateParam)}` : ''}${gradeParam ? `&grade=${encodeURIComponent(gradeParam)}` : ''}${isInternational ? '&int=true' : ''}`}
                className="modern-button mt-4 md:mt-6 inline-flex"
              >
                {language === "zh" ? "提交回忆" : "Submit Memory"}
              </a>
            )}
          </div>
        </div>
      ) : (
        <div className="space-y-6">
          {/* 年份筛选器 */}
          <div className="relative">
            <button
              onClick={() => setYearFilterOpen(!yearFilterOpen)}
              className="glass-panel inline-flex items-center gap-2 px-3 py-1.5 text-sm font-medium transition-colors rounded-lg"
              aria-expanded={yearFilterOpen}
              aria-haspopup="true"
            >
              <Filter className="h-4 w-4" />
              <span>
                {language === "zh" ?
                  selectedYear ? `${selectedYear}年` : "全部年份" :
                  selectedYear ? `Year ${selectedYear}` : "All Years"
                }
              </span>
              {yearFilterOpen ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </button>
            
            {yearFilterOpen && (
              <div className="absolute top-full left-0 mt-1 z-10 py-1 rounded-lg shadow-lg glass-panel min-w-[150px]">
                <button
                  onClick={() => handleYearFilter(null)}
                  className={`block w-full text-left px-4 py-2 text-sm hover:bg-secondary/50 ${!selectedYear ? "text-primary" : ""}`}
                >
                  {language === "zh" ? "全部年份" : "All Years"}
                </button>
                {availableYears.map(year => (
                  <button
                    key={year}
                    onClick={() => handleYearFilter(year.toString())}
                    className={`block w-full text-left px-4 py-2 text-sm hover:bg-secondary/50 ${selectedYear === year.toString() ? "text-primary" : ""}`}
                  >
                    {year} {language === "zh" ? "年" : ""}
                  </button>
                ))}
              </div>
            )}
          </div>
          
          {/* 考试列表 */}
          <div className="space-y-5">
            {examNames.map(examName => (
              <div key={examName} className="glass-panel">
                <button 
                  onClick={() => toggleExam(examName)}
                  className="w-full p-4 md:p-5 flex items-center justify-between gap-3"
                >
                  <h2 className="text-lg md:text-xl font-semibold text-left flex items-center gap-2">
                    <FileText className="h-5 w-5 text-primary" />
                    <span>{examName}</span>
                  </h2>
                  {expandedExams.includes(examName) ? (
                    <ChevronUp className="h-5 w-5" />
                  ) : (
                    <ChevronDown className="h-5 w-5" />
                  )}
                </button>
                
                {expandedExams.includes(examName) && (
                  <div className="space-y-4 p-4 md:p-5 pt-0 border-t" style={{ borderColor: 'hsl(var(--border) / 0.4)' }}>
                    {groupedMemories[examName].map((memory, idx) => (
                      <div 
                        key={memory.id} 
                        className="space-y-3 p-3 md:p-4 rounded-xl transition-all"
                        style={{ backgroundColor: 'hsl(var(--card) / 0.6)' }}
                      >
                        <div className="flex flex-wrap gap-2 text-sm font-normal items-center justify-between">
                          <div className="flex items-center gap-2">
                            <User className="h-4 w-4 text-primary" />
                            <span>{memory.signature || (language === "zh" ? "匿名用户" : "Anonymous")}</span>
                            {memory.international && (
                              <span className="text-xs px-1.5 py-0.5 bg-blue-500/20 text-blue-500 rounded">
                                INT
                              </span>
                            )}
                            {memory.examDate && (
                              <span className="text-xs px-1.5 py-0.5 bg-primary/10 text-primary rounded flex items-center gap-1">
                                <Calendar className="h-3 w-3" />
                                {memory.examDate}
                              </span>
                            )}
                          </div>
                          <time className="text-xs opacity-60">
                            {language === "zh" ?
                              "分享于 " + new Date(memory.timestamp).toLocaleString('zh-CN') :
                              "Shared on " + new Date(memory.timestamp).toLocaleString('en-US')
                            }
                          </time>
                        </div>
                        <pre 
                          className="whitespace-pre-wrap font-normal text-base leading-relaxed p-3 md:p-4 rounded-lg"
                          style={{ backgroundColor: 'hsl(var(--secondary) / 0.3)' }}
                        >
                          {memory.questions}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// 创建一个包含 useSearchParams 的子组件
function SearchParamsHandler() {
  const { setLanguage } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  
  useEffect(() => {
    const intParam = searchParams.get("int");
    if (intParam === "true") {
      // 设置语言为英文
      setLanguage("en");
    }
  }, [router, searchParams, setLanguage]);
  
  return null;
}

export default function ViewerPage() {
  return (
    <Suspense fallback={
      <div className="flex justify-center py-12">
        <Loader2 className="h-10 w-10 animate-spin text-primary" />
      </div>
    }>
      {/* 使用 Suspense 包裹使用 useSearchParams 的组件 */}
      <Suspense fallback={null}>
        <SearchParamsHandler />
      </Suspense>
      <ViewerPageContent />
    </Suspense>
  );
} 